﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TowerSensor : MonoBehaviour {
    public Ticker ticker = new Ticker(10, false);

    public float SensorRange;
    public int ValidUnitCount; //周围士兵中最多的士兵相比于其他方净多出的数量
    public PlayerType MaxUnitOwner;
    public bool DrawGizmos;
    Dictionary<PlayerType, int> ownerUnitCountDic = new Dictionary<PlayerType, int>();

    private void Update()
    {
        if(ticker.Tick())
        {
            var colliders =  Physics.OverlapSphere(transform.position, SensorRange, LayerMask.GetMask(LayerNameSet.Unit));
            ownerUnitCountDic.Clear();
            foreach(var c in colliders)
            {
                var unit = c.GetComponent<Warrior>();
                if (unit == null) continue;
                if (ownerUnitCountDic.ContainsKey(unit.unitOwner))
                    ownerUnitCountDic[unit.unitOwner]++;
                else
                    ownerUnitCountDic.Add(unit.unitOwner, 1);
            }
            if(ownerUnitCountDic.Count>0)
            {
                var MostInflencePlayer = ownerUnitCountDic.MQ_Max((x, y) => x.Value > y.Value ? 1 : -1);
                int OtherUnitCount = ownerUnitCountDic.MQ_Sum((KeyValuePair<PlayerType, int> x) => x.Key == MostInflencePlayer.Key ? 0 : MostInflencePlayer.Value,
                    (x, y) => x + y);
                if (MostInflencePlayer.Value > OtherUnitCount)
                {
                    MaxUnitOwner = MostInflencePlayer.Key;
                    ValidUnitCount = MostInflencePlayer.Value - OtherUnitCount;
                }
                else MaxUnitOwner = PlayerType.None;
            }
            else
            {
                MaxUnitOwner = PlayerType.None;
            }
        }
    }
    private void OnDrawGizmos()
    {
        if (DrawGizmos)
        {
            Gizmos.DrawWireSphere(transform.position, SensorRange);
        }
    }

    
}
